package com.jie.other.compose.study04

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jie.other.compose.data.ExploreModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

const val MAX_PEOPLE = 4

class Study04ViewModel : ViewModel() {

    private val dataRepository = Study04Repository()
    private val _suggestList = MutableStateFlow<List<ExploreModel>>(emptyList())

    val mSuggestList = _suggestList.asStateFlow()

    init {
        _suggestList.value = dataRepository.destinations
    }

    /**
     * 更新列表
     */
    fun updatePeople(people : Int) {
        viewModelScope.launch {
            if (people > MAX_PEOPLE) {
                _suggestList.value = emptyList()
            } else {
                // 打乱列表并返回
                val newList = withContext(Dispatchers.Default) {
                    dataRepository.destinations
                        .shuffled(Random(people * (1..100).shuffled().first()))
                }
                _suggestList.value = newList
            }
        }
    }

    fun toDestinationChanged(newDestination : String) {
        viewModelScope.launch {
            val newList = withContext(Dispatchers.Default) {
                dataRepository.destinations
                    .filter {
                        it.city.nameToDisplay.contains(newDestination)
                    }
            }
            _suggestList.value = newList
        }
    }

}